package com.zxh.utils;


import com.zxh.filters.TPMonitorFilter;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
// 每隔5s打印一次最近1分钟内每个方法的TP90、TP99的耗时情况
public class TP9099Report implements Runnable {

    @Override
    public void run() {
        System.out.println("每隔5s打印一次最近1分钟内每个方法的TP90、TP99的耗时情况");
        HashMap<String, TreeSet<TPMonitorFilter.TPsion>> statistics =  TPMonitorFilter.requestTpsion;

        Set<Map.Entry<String, TreeSet<TPMonitorFilter.TPsion>>> set = statistics.entrySet();
        for(Map.Entry<String, TreeSet<TPMonitorFilter.TPsion>> entry : set) {
            String service = entry.getKey();
            TreeSet<TPMonitorFilter.TPsion> value = entry.getValue();
            report(value, service);
        }

        System.out.println("==================================");
    }

    protected void report(TreeSet<TPMonitorFilter.TPsion> allTPs, String service) {
        synchronized (allTPs) {
            long startTime = System.currentTimeMillis() - 60 * 1000; //获取一分钟前的时间
            if(allTPs.size() == 0)
            {
                System.out.println("allTPs is null");
            }
            for (TPMonitorFilter.TPsion data : allTPs) {
                if(data.sendTime < startTime) {
                    allTPs.remove(data);
                }
            }

            int all = allTPs.size();

            int tp90Point = (int)(all * 0.90);//TP90
            int tp99Point = (int)(all * 0.99);//TP99

            TPMonitorFilter.TPsion percent90PointData = null;
            TPMonitorFilter.TPsion percent99PointData = null;
            int counter = 1;
            for (TPMonitorFilter.TPsion data : allTPs) {
                if(counter == tp90Point) {
                    percent90PointData = data;
                } else if(counter == tp99Point) {
                    percent99PointData = data;
                }
                counter++;
            }

            System.out.println("最近1分钟内"+service+"方法的TP90、TP99的耗时情况：");
            System.out.println("  TP90 耗时情况：" + percent90PointData.spendTime);
            System.out.println("  TP99 耗时情况：" + percent99PointData.spendTime);
        }
    }
}